<template>
  <p-card>
    <p-page-header
            style="border: 1px solid rgb(235, 237, 240)"
            title="生成入库检送检任务（成品）"
    >
      <template slot="extra">
        <!--<p-popconfirm
                title="确定要提交吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm=""
                @cancel="cancel"
        >
          <p-button type="primary">提交</p-button>
        </p-popconfirm>-->

        <p-popconfirm
                style="margin-left: 16px;"
                title="确定要提交吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="submitData"
                @cancel="cancel"
        >
          <p-button type="primary" >提交</p-button>
        </p-popconfirm>

        <p-button @click="backToIndex">取消</p-button>
      </template>
    </p-page-header>
    <h4 class="title">基础信息</h4>

    <p-form-model
            ref="baseInfoData"
            :model="baseInfoData"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
    >
      <p-row :gutter="24">
        <p-col :span="8">
          <p-form-model-item ref="inspectBillno" label="送检单号" prop="inspectBillno">
            <p-input
                    readOnly
                    v-model="baseInfoData.inspectBillno"
                    @blur="
          () => {
            $refs.inspectBillno.onFieldBlur();
          }
        "
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="sendInspecter" label="送检人" prop="sendInspecter">
            <p-input
                    readOnly
                    v-model="baseInfoData.sendInspecter"
                    @blur="
          () => {
            $refs.sendInspecter.onFieldBlur();
          }
        "
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="sendInspectTime" label="送检时间" prop="sendInspectTime">
            <p-input
                    readOnly
                    v-model="baseInfoData.sendInspectTime"
                    @blur="
          () => {
            $refs.sendInspectTime.onFieldBlur();
          }
        "
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="waitInspectNumber" label="待检数量" prop="waitInspectNumber">
            <p-input
                    type="number"
                    readOnly
                    v-model="baseInfoData.waitInspectNumber"
                    @blur="
          () => {
            $refs.waitInspectNumber.onFieldBlur();
          }
        "
            />
          </p-form-model-item>
        </p-col>

        <p-col :span="8" >
          <p-form-model-item ref="inbankIndex" label="入库库位" prop="inbankIndex">

           <!-- <p-input
                    readOnly
                    v-model="baseInfoData.inbankIndex"
            />-->
            <p-select v-model="baseInfoData.inbankIndexNo" showSearch >
              <p-select-option
                      v-for="(item,index) in inbankIndexOptions"
                      :key="index"
                      :value="item.storageno"
              >{{item.storageno}}</p-select-option>
            </p-select>

            <p style="color:red" v-if="selectBankList.length>1">只能选择同一库位</p>
          </p-form-model-item>
        </p-col>
        <!-- <p-col :span="8">
           <p-form-model-item ref="inbankBank" label="入库仓库" prop="inbankBank" >
             <p-select v-model="baseInfoData.inbankBank"  placeholder="please select your zone" readOnly>
               <p-select-option
                       v-for="(item,index) in inbankBankOptions"
                       :key="index"
                       :value="item.inbankBank"
               >{{item.inbankBank}}</p-select-option>
             </p-select>
           </p-form-model-item>
         </p-col>-->
      </p-row>
    </p-form-model>



    <h4 class="title">送检维度</h4>
    <p-form-model
            ref="inspectionConditions"
            :model="baseInfoData"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
    >
      <p-row :gutter="24">
        <p-col :span="8">
          <p-form-model-item ref="mcode" label="品号" prop="mcode">
            <p-select
                    allowClear
                    show-search
                    v-model="baseInfoData.mcode"
                    placeholder="请选择产品"
                    @change="productionSelectChange"

            >
              <p-select-option
                      v-for="(item) in productionList"
                      :key="item.mcode"
                      :value="item"
              >{{item}}</p-select-option>


            </p-select>
          </p-form-model-item>
        </p-col>

        <p-col :span="8">
          <p-form-model-item ref="processbillnoValues" label="工单" prop="processbillnoValues">
            <p-select  mode="multiple" v-model="processbillnoValues" placeholder="请选择工单" @change="processbillnoSelectChange" >
              <p-select-option
                      v-for="(item,index) in processbillnoList"
                      :key="index"
                      :value="item"
              >{{item}}</p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>

        <p-col :span="8">
          <p-form-model-item ref="lineValues" label="线别" prop="lineValues">
            <p-select  mode="multiple" v-model="lineValues" placeholder="请选择线别" @change="lineSelectChange" >
              <p-select-option
                      v-for="(item,index) in lineList"
                      :key="index"
                      :value="item.linename"
              >{{item.linename}}</p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>

        <p-col :span="8">
          <p-form-model-item ref="palletNoValues" label="栈板" prop="palletNoValues">
            <p-select  mode="multiple" v-model="palletNoValues" placeholder="请选择栈板" @change="palletNoSelectChange" >
              <p-select-option
                      v-for="(item,index) in palletNoList"
                      :key="index"
                      :value="item"
              >{{item}}</p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>


        <p-col :span="8">
          <p-form-model-item ref="screeningSn" label="SN" prop="screeningSn">
            <p-select mode="multiple" v-model="snpnValues" placeholder="请选择SN/PN" @change="snpnSelectChange">
              <p-select-option
                      v-for="(item,index) in snpnList"
                      :key="index"
                      :value="item"
              >{{item}}</p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>

      </p-row>
    </p-form-model>

    <h4 class="title">送检产品明细</h4>
   <!-- <div style="margin-top: 10px;margin-bottom: 10px">
      <p-button type="primary" @click="openDetailBankBtn">修改库位</p-button>
    </div>-->

    <p-alert v-if="tipsState==1"  message="无可选的送检产品明细列表" type="warning" show-icon />
    <p-alert v-if="tipsState==2"  message="请勾选送检产品明细" type="info" show-icon />
    <div v-if="tipsState==3" class="ant-alert ant-alert-success"  style="margin-bottom: 16px;">
      <p-icon type="check-circle" style="background-color: #33cc66;border-radius: 60px;color:white;font-size:20px" />
      <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
      <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
      <a style="margin-left: 24px" @click="clearSelectRow">清空</a>
    </div>

    <p-table
            :columns="inspectionProductsColumns"
            :data-source="inspectionProductsnData"
            class="components-table-demo-nested"
            bordered
            style="margin-top:10px;"
            :rowSelection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps:getCheckboxProps
      }"
            :customRow="setRow"
    >
      <template slot="qty" slot-scope="text,record">
        <div v-if="baseInfoData.controlsType==1">1</div>
        <div v-else>{{text}}</div>
      </template>

    </p-table>


    <p-modal v-model="detailBankVisible" title="修改库位" @ok="updateDetailBank">
      <p-row :gutter="24">
        <p-col :span="5">
          生产工单：
        </p-col>
        <p-col :span="19">
          <p-select v-model="cdProductionno" style="width:300px"  >
            <p-select-option
                    v-for="(item,index) in scgdList"
                    :key="index"
                    :value="item"
            >{{item}}</p-select-option>
          </p-select>
        </p-col>
      </p-row>

      <p-row :gutter="24">
        <p-col :span="5">
          入库库位：
        </p-col>
        <p-col :span="19">
          <p-select v-model="cdBank" style="width:300px">
            <p-select-option
                    v-for="(item,index) in inbankIndexOptions"
                    :key="index"
                    :value="item.id"
            >{{item.storagename}}</p-select-option>
          </p-select>
        </p-col>
      </p-row>
    </p-modal>



  </p-card>
</template>

<script>
  // import { JeecgListMixin } from "@/mixins/JeecgListMixin";
  import { api } from "@/api/manage";
  import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
  import { filterObj } from "@/utils/util";
  import Vue from "vue";
  import {getAction,putAction,postAction} from "../../../api/manage";

  export default {
    name: "MesQcInfoCFullList",
    // mixins: [JeecgListMixin],
    props:['mqVisible','mqLoad','mqData'],
    data() {
      return {
        labelCol: { span: 7 },
        wrapperCol: { span: 16 },
        selectedRowKeys: [],
        selectedRows: [],
        tipsState:1,

        selectBankList:[],

        //产品list
        productionList:[],
        productAllInfo:[],
        productionMap:[],

        //工序工单list
        processbillnoList:[],
        processbillnoMap:[],

        //生产工单list
        productionnoList:[],
        productionnoMap:[],

        //SN、PN list
        snpnList:[],
        snpnMap:[],

        //线体list
        lineList:[],
        lineMap:[],

        //栈板
        palletNoList:[],
        palletNoMap:[],

        processbillnoValues:[],
        productionnoValues:[],
        snpnValues:[],
        lineValues:[],
        palletNoValues:[],

        detailBankVisible:false,

        rules: {
          inspectBillno: [
            {
              required: true,
              message: "Please input Activity name",
              trigger: "blur",
            },
          ],
          sendInspecter: [
            {
              required: true,
              message: "Please input Activity name",
              trigger: "blur",
            },
          ],
          sendInspectTime: [
            {
              required: true,
              message: "Please input Activity name",
              trigger: "blur",
            },
          ],
          waitInspectNumber: [
            {
              required: true,
              message: "Please input Activity name",
              trigger: "blur",
            },
          ],
          controlsType: [
            {
              required: true,
              message: "Please input Activity name",
              trigger: "blur",
            },
          ],

          mname: [
            {
              required: true,
              message: "Please input Activity name",
              trigger: "blur",
            },
          ],


          inbankIndex: [
            {
              required: false,
              message: "Please input Activity name",
              trigger: "change",
            },
          ],
          inbankBank: [
            {
              required: true,
              message: "Please input Activity name",
              trigger: "blur",
            },
          ],
        },


        modal2Visible: false,
        baseInfoData: {
          //基础信息
          inspectBillno: "", //送检单号
          sendInspecter: "", //送检人
          sendInspectTime: "", //送检时间
          waitInspectNumber: "", //待检数量
          controlsType: 1, //管控方式
          mid: {},
          mcode: '', //产品编码
          mname: "", //产品名称
          processbillno: '', //工序工单
          productionno:' 1', //生产工单
          pnSendNumber: 0, //PN实际送检数量
          screeningSn: '', //SN/PN
          inbankIndex: '', //入库库位
          inbankBank: '', //入库仓库
        },
        controlsTypeOptions: [
          //入库仓库选项
          {
            name: "SN",
            value: 1,
          },
          {
            name: "PN",
            value: 2,
          },
        ],

        processbillnoOptions: [

        ],
        productionnoOptions: [

        ],
        screeningSnOptions: [

        ],
        inbankIndexOptions: [

        ],

        inbankIndexOptionsMap:[],
        inbankBankOptions: [

        ],
        inspectionProductsColumns: [
          { title: "序号",
            dataIndex: "",
            key: "rowIndex",
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }, },
          { title: "线体", dataIndex: "linename", key: "linename" },
          {
            title: "生产工单",
            dataIndex: "productionno",
            key: "productionno",
          },
          { title: "工序工单", dataIndex: "processbillno", key: "processbillno" },
          { title: "产品编码", dataIndex: "mcode", key: "mcode" },
          { title: "产品名称", dataIndex: "mname", key: "mname" },
          { title: "栈板号/容器码", dataIndex: "palletNo", key: "palletNo" },
          { title: "SN", dataIndex: "sn", key: "sn" },
          { title: "数量", dataIndex: "qty", key: "qty",scopedSlots: {customRender: "qty"} },
          { title: "入库库位", dataIndex: "wareLocationCode", key: "wareLocationCode" },
          { title: "状态", dataIndex: "status", key: "status",
            customRender: (text) => {
              if (!text) {
                return "";
              } else {
                return text==1?'未检':'已检';
              }
            },
          },
        ],
        inspectionProductsnData: [

        ],
        firstInspectionProductsnData:[],


        scgdList:[],
        cdProductionno:'',
        cdBank:'',
      };
    },
    computed: {
      // checkBox属性设置
      getCheckboxProps(record) {
        return (record) => ({
          props: {
            // defaultChecked: record.key === this.modal2InspectionData[0].key,
          },
        });
      },
    },

    created() {this.mqListener()},

    methods: {
      mqListener(){

        this.initInbankIndexOptions();
        this.initData(this.mqData);

      },
      backToIndex(){
        let mqData = this.mqData;
        this.$emit('update:mqVisible', 1);
        this.$emit('update:mqLoad', false);
        mqData.id = 0;
        this.$emit('update:mqData', mqData);
      },


      setRow(record) {
        return {
          on: {
            click: () => {
              let rowKeys = this.selectedRowKeys;
              if (rowKeys.length > 0 && rowKeys.includes(record.key)) {
                rowKeys.splice(rowKeys.indexOf(record.key), 1);
              } else {
                rowKeys.push(record.key);
              }
              this.selectedRowKeys = rowKeys;
              console.log(this.selectedRowKeys);
            },
          },
        };
      },
      onSelectChange(selectedRowKeys,selectedRows) {
        console.log("selectedRowKeys changed: ", selectedRowKeys);
        console.log("selectedRows changed: ", selectedRows);
        this.selectedRowKeys = selectedRowKeys;
        this.setTipsState();
        this.setPnFactQty(selectedRowKeys);

        let bankList = [];
        if(selectedRows){
          let qtyTotal = 0;
          selectedRows.forEach(item=>{
            qtyTotal = qtyTotal  + item.qty;
            if(item.wareLocationCode&&item.wareLocationCode!=''){
              if(bankList.indexOf(item.wareLocationCode)==-1){
                bankList.push(item.wareLocationCode)
              }
            }
          })
          this.baseInfoData.waitInspectNumber = qtyTotal;

          this.selectBankList = bankList;
          if(bankList.length==1){
            this.baseInfoData.inbankIndexNo = bankList[0]
          }else{
            this.baseInfoData.inbankIndexNo = '';
          }

        }
      },

      //设置pn实际送检数量
      setPnFactQty(selectedRowKeys){
        if(this.baseInfoData.controlsType==2){
          let map = this.listToMap(this.inspectionProductsnData,'key');
          let result = 0;
          selectedRowKeys.forEach(item=>{
            if(map[item]){
              result+=map[item].qty;
            }
          })
          this.baseInfoData.pnSendNumber = result;
        }

      },

      //设置提示状态
      setTipsState(){
        if(this.inspectionProductsnData.length==0){
          this.tipsState=1;
        }else{
          if(this.selectedRowKeys.length==0){
            this.tipsState=2;
          }else{
            this.tipsState=3;
          }
        }
      },


      openDetailBankBtn(){
        this.detailBankVisible = true;
        this.cdProductionno = '';
        this.cdBank = '';
      },

      updateDetailBank(){
        if(this.cdProductionno!=''&&this.cdBank!=''){
          let result = this.inbankIndexOptionsMap[this.cdBank]?this.inbankIndexOptionsMap[this.cdBank].storageno:'';

          this.inspectionProductsnData.forEach(item=>{
            if(item.productionno==this.cdProductionno){
              item.wareLocationCode = result;
            }
          })
        }

        this.detailBankVisible = false;
      },

      /**
       * 数据初始化
       */
      initData(query){

        if(!query.id){
          this.$message.warning("请通过入库检验清单选择单号进入！");
        }else{
          let id = query.id;
          getAction('/mes-quality/mesQcIntoWarehouseInspectTask/selectById/'+id).then(res=>{
            if(res.success){
              if(res.code!=0){
                this.$message.warning(res.msg)
              }
              let data = res.data;

              data.sendInspecter = this.$store.state.user.name;
              data.waitInspectNumber = 0;
              if(!this.baseInfoData.processbillno||this.baseInfoData.processbillno===""){
                this.processbillnoValues = [];
              }else{
                this.processbillnoValues = this.baseInfoData.processbillno.split(",");
              }


              let proDetailsList = data.proDetailsList;

              let productArray = [];
              let productAllInfo = [];

              let scgdList = [];

              let key  = 1;
              proDetailsList.forEach(item=>{
                item.key = key;
                key = key + 1;
                let mcode = item.mcode;

                if(scgdList.indexOf(item.productionno)==-1){
                  scgdList.push(item.productionno);
                }

                if(productArray.indexOf(item.mcode)==-1){
                  productArray.push(item.mcode);
                  let pmEntity = {
                    mcode:mcode,
                    workbillnoSet:new Set(),
                    workbillnoList:[],
                    lineSet:new Set(),
                    lineList:[],
                    palletNoSet:new Set(),
                    palletNoList:[],
                    snSet:new Set(),
                    snList:[],
                  };

                  productAllInfo.push(pmEntity)

                }

                let  pIndex = productArray.indexOf(item.mcode);


                //processbillno
                if(!productAllInfo[pIndex].workbillnoSet.has(item.processbillno)){
                  productAllInfo[pIndex].workbillnoSet.add(item.processbillno);
                  productAllInfo[pIndex].workbillnoList.push(
                          item.processbillno
                  )
                }

                if(!productAllInfo[pIndex].lineSet.has(item.lineno)){
                  productAllInfo[pIndex].lineSet.add(item.lineno);
                  productAllInfo[pIndex].lineList.push(
                          {lineno:item.lineno,linename:item.linename}
                  )
                }


                if(!productAllInfo[pIndex].palletNoSet.has(item.palletNo)){
                  productAllInfo[pIndex].palletNoSet.add(item.palletNo);
                  productAllInfo[pIndex].palletNoList.push(
                          item.palletNo
                  )
                }

                if(!productAllInfo[pIndex].snSet.has(item.sn)){
                  productAllInfo[pIndex].snSet.add(item.sn);
                  productAllInfo[pIndex].snList.push(
                          item.sn
                  )
                }



              })
              this.firstInspectionProductsnData = proDetailsList;
              this.inspectionProductsnData = proDetailsList;

              this.productionList = productArray;
              this.productAllInfo = productAllInfo;


              this.scgdList = scgdList;

              this.baseInfoData = data;


              this.setTipsState();
            }else{
              this.$message.warning(res.msg);
            }
          })
        }
      },

      //清空已勾选的检验项目明细
      clearSelectRow(){
        this.selectedRowKeys= [];
        this.selectedRows= [];
        this.setTipsState();
        if(this.baseInfoData.controlsType==2){
          this.baseInfoData.pnSendNumber=0;
        }

        this.selectBankList = [];
        this.baseInfoData.wareLocationCode = '';
      },

      //加载入库库位及其对应仓库
      initInbankIndexOptions(){


        getAction('/basic-business/auto/stStorage/all').then(res=>{
          if(res.success){
            this.inbankIndexOptions = res.data;
            this.inbankIndexOptionsMap = this.listToMap(this.inbankIndexOptions,'id');
          }
        })
        /* this.inbankIndexOptions = data;*/
      },
      //加载送检产品明细列表，并且从中取出产品编码下拉框的数据集
      initInspectionProductsnData(){
        let  inspectionProductsnData  = [
          {
            lineid:2002,
            linename: "A0002",
            productionno: "SCGD111",
            processbillno: "GXGD111",
            mid:1001,
            mcode: "M1001",
            mname: "产品1001",
            palletNo: "ZB111",
            snpn: "x1001",
            qty: 88,
            status: 1,
          },
          {
            lineid:2001,
            linename: "A0001",
            productionno: "SCGD222",
            processbillno: "GXGD222",
            mid:1001,
            mcode: "M1001",
            mname: "产品1001",
            palletNo: "ZB111",
            snpn: "x1002",
            qty: 73,
            status: 1,
          },

          {
            lineid:2002,
            linename: "A0002",
            productionno: "SCGD333",
            processbillno: "GXGD333",
            mid:1002,
            mcode: "M1002",
            mname: "产品1002",
            palletNo: "ZB222",
            snpn: "x1003",
            qty: 61,
            status: 1,
          },
          {
            lineid:2001,
            linename: "A0001",
            productionno: "SCGD444",
            processbillno: "GXGD444",
            mid:1002,
            mcode: "M1002",
            mname: "产品1002",
            palletNo: "ZB222",
            snpn: "x1004",
            qty: 68,
            status: 1,
          },

          {
            lineid:2001,
            linename: "A0001",
            productionno: "SCGD555",
            processbillno: "GXGD555",
            mid:1001,
            mcode: "M1001",
            mname: "产品1001",
            palletNo: "ZB333",
            snpn: "x1005",
            qty: 23,
            status: 1,
          },
          {
            lineid:2002,
            linename: "A0002",
            productionno: "SCGD666",
            processbillno: "GXGD666",
            mid:1002,
            mcode: "M1002",
            mname: "产品1002",
            palletNo: "ZB333",
            snpn: "x1006",
            qty: 61,
            status: 1,
          },
        ];
        //循环设置key   一定要key！用于后续联动数据
        for(let i=0;i<inspectionProductsnData.length;i++){
          inspectionProductsnData[i].key = i+1;
        }
        this.inspectionProductsnData = inspectionProductsnData;
        this.firstInspectionProductsnData = inspectionProductsnData;

        //TODO 产品直接先假数据写死，后续可能会通过上面的假明细做groupBy
        let productionList = [
          { mid:1001,
            mcode: "M1001",
            mname: "产品1001",},
          { mid:1002,
            mcode: "M1002",
            mname: "产品1002",},
        ];

        this.productionList = productionList;
        this.productionMap = this.listToMap(productionList,'mid');

      },

      //封装listToMap
      listToMap(list,name){
        let map = {};
        for(let i in list){
          map[list[i][name]] = list[i];
        }
        return map;
      },
      /**
       * 产品下拉框控件方法
       * @param input
       * @param option
       * @returns {boolean}
       */
      mcodeFilterOption(input, option){
        return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      /**
       * 产品下拉框change事件
       */
      productionSelectChange(value){



        //清空已选择的工序工单,生产工单
        this.processbillnoValues = [];
        this.processbillnoMap=[];
        this.processbillnoList  = [];
        this.productionnoValues = [];
        this.productionnoMap = [];
        this.productionnoList = [];
        this.snpnValues = [];
        this.snpnList = [];
        this.snpnMap = [];
        this.lineValues = [];
        this.lineList = [];
        this.lineMap = [];
        this.palletNoValues = [];
        this.palletNoList=[];
        this.palletNoMap = [];


        if(!this.baseInfoData.mcode||this.baseInfoData.mcode==''){

          console.log('none')
          //清空已选择的工序工单,生产工单
          this.processbillnoValues = [];
          this.processbillnoMap=[];
          this.processbillnoList  = [];
          this.productionnoValues = [];
          this.productionnoMap = [];
          this.productionnoList = [];
          this.snpnValues = [];
          this.snpnList = [];
          this.snpnMap = [];
          this.lineValues = [];
          this.lineList = [];
          this.lineMap = [];
          this.palletNoValues = [];
          this.palletNoList=[];
          this.palletNoMap = [];

          this.inspectionProductsnData = this.firstInspectionProductsnData;


          this.clearSelectRow();
        }else{
          console.log('has')

          let productArray = this.productionList ;
          console.log(productArray)

          let productAllInfo = this.productAllInfo;
          let index = productArray.indexOf(this.baseInfoData.mcode);

          console.log(productAllInfo[index])
          if(index != -1){
            this.processbillnoList  = productAllInfo[index].workbillnoList;
            this.lineList  = productAllInfo[index].lineList;
            this.palletNoList  = productAllInfo[index].palletNoList;
            this.snpnList  = productAllInfo[index].snList;
          }else{
            this.processbillnoList = [];
            this.lineList  = [];
            this.palletNoList  = [];
            this.snList  = [];
          }


          this.resetSendProductDetail();
        }



      },
      /**
       * 管控方式下拉框change事件
       */
      controlsTypeChange(value){
        this.setPnFactQty(this.selectedRowKeys);
      },
      /**
       * 工序工单下拉框change事件
       */
      processbillnoSelectChange(value){
        this.resetSendProductDetail();
      },
      //线别下拉框
      lineSelectChange(value){
        this.resetSendProductDetail();
      },
      //栈板下拉框
      palletNoSelectChange(value){
        this.resetSendProductDetail();
      },
      /**
       * 生产下拉框change事件
       */
      productionnoSelectChange(value){
        this.resetSendProductDetail();
      },
      //snpn
      snpnSelectChange(value){
        this.resetSendProductDetail();
      },
      //库位下拉change
      inbankIndexSelectChange(){
        this.baseInfoData.inbankBank = '';
        //{inbankIndex:"入库库位1",inbankBankOptions:[{inbankBank:"仓库1",},{inbankBank:"仓库2",}]},
        let map = this.listToMap(this.inbankIndexOptions,'id');

        if(map[this.baseInfoData.inbankIndexId]){
          this.baseInfoData.inbankIndexNo = map[this.baseInfoData.inbankIndexId].storageno;
          this.baseInfoData.inbankIndex = map[this.baseInfoData.inbankIndexId].storagename;

        }
      },

      /**
       * 重置送检产品明细
       */
      resetSendProductDetail(){
        this.clearSelectRow();
        let mcode = this.baseInfoData.mcode;

        let processbillnoValues = this.processbillnoValues;
        let snpnValues = this.snpnValues;
        let lineValues = this.lineValues;
        let palletNoValues = this.palletNoValues;


        let firstData = this.firstInspectionProductsnData;
        let dataByMid = [];
        let usedKey = new Set();
        let resultData = [];

        firstData.forEach(item=>{
          if(mcode==item.mcode){
            dataByMid.push(item);
          }
        })

        console.log(dataByMid)

        /*if(processbillnoValues.length>0&&lineValues.length>0&&snpnValues.length>0&&palletNoValues.length>0){
          dataByMid.forEach(item=>{
            item.processbillnoFlag  = false;
            item.linenameFlag = false;
            processbillnoValues.forEach(j=>{
              if(item.processbillno==j){
                item.processbillnoFlag = true;
              }
            })
            lineValues.forEach(o=>{
              if(item.linename == o){
                item.linenameFlag = true;
              }

            })

            if(item.processbillnoFlag==true&&item.linenameFlag==true){
              resultData.push(item)
            }
          })

          this.inspectionProductsnData = resultData;

        }else*/ if(processbillnoValues.length>0||lineValues.length>0||snpnValues.length>0||palletNoValues.length>0){
          /*let dataMap1 = this.listToMap(dataByMid,'processbillno');*/
          processbillnoValues.forEach(item=>{
            /* if(dataMap1[item]){
               usedKey.add(dataMap1[item].key);
             }*/
            dataByMid.forEach(j=>{
              if(j.processbillno==item){
                usedKey.add(j.key);
              }
            })
          })
          /* let dataMap2 = this.listToMap(dataByMid,'linename');*/
          lineValues.forEach(item=>{
            /*if(dataMap2[item]){
              usedKey.add(dataMap2[item].key);
            }*/
            dataByMid.forEach(j=>{
              if(j.linename==item){
                usedKey.add(j.key);
              }
            })
          })

          /*let dataMap4 = this.listToMap(dataByMid,'sn');*/
          snpnValues.forEach(item=>{
            /* if(dataMap4[item]){
               usedKey.add(dataMap4[item].key);
             }*/
            dataByMid.forEach(j=>{
              if(j.sn==item){
                usedKey.add(j.key);
              }
            })
          })

          /*let dataMap5 = this.listToMap(dataByMid,'palletNo');*/
          palletNoValues.forEach(item=>{
            /*if(dataMap5[item]){
              usedKey.add(dataMap5[item].key);
            }*/
            dataByMid.forEach(j=>{
              if(j.palletNo==item){
                usedKey.add(j.key);
              }
            })
          })

          let dataMap3 = this.listToMap(dataByMid,'key');
          for(let key of usedKey){
            if(dataMap3[key]){
              resultData.push(dataMap3[key]);
            }
          }

          this.inspectionProductsnData = resultData;
        }else{
          this.inspectionProductsnData =dataByMid;
        }

        this.setTipsState();
      },




      /**
       * 加载工序工单
       */
      initProcessbillnoList(){
        //TODO 2.“工序工单”，根据产品编码自动带出未检的“工序工单”，选择需要送检的工序工单，支持多选，自动带出生产工单


      },

    checkPalletWithSn(list1,list2){
        let result = false;


        let fcIndex = [];
        let firstCount = [];

        list1.forEach(item=>{
          if(fcIndex.indexOf(item.palletNo)==-1){
            fcIndex.push(item.palletNo);

            firstCount.push({name:item.palletNo,count:0,sCount:0})
          }

          let index = fcIndex.indexOf(item.palletNo);


          firstCount[index].count =  firstCount[index].count + 1;
        })

      list2.forEach(item=>{
        if(fcIndex.indexOf(item.palletNo)!=-1){
          let index = fcIndex.indexOf(item.palletNo);
          firstCount[index].sCount =  firstCount[index].sCount + 1;
        }
      })

      let flag = 0;
      firstCount.forEach(item=>{
        if(item.count!=item.sCount){
         flag = flag +1;
        }
      })

      if(flag>0){
        result = false;
      }else{
        result = true;
      }

      console.log('-----------------------------------------------')
      console.log(result)

        return result;
    },

      //提交数据
      submitData(){
        let flag = true;
        let data = this.baseInfoData;


        /* if(!data.inbankIndex||data.inbankIndex===''){
           flag = false;
           this.$message.error("请选择入库库位！");
         }*/
        /*        if(!data.inbankBank||data.inbankBank===''){
                  flag = false;
                  this.$message.error("请选择入库仓库！");
                }*/

        let map = this.listToMap(this.inspectionProductsnData,'key');
        let datailList  = [];
        this.selectedRowKeys.forEach(item=>{
          if(map[item]){
            datailList.push(map[item]);
          }
        })

        if(datailList.length>0){
          if(!data.mcode||data.mcode===''){
            flag = false;
            this.$message.error("请选择产品编码！");
          }

          if(!(this.checkPalletWithSn(datailList,this.inspectionProductsnData))){
            flag = false;
            this.$message.error('同一栈板SN必须一起送检');
          }
        }

        data.proDetailsList = datailList;



        if(flag){


          data.productionno = this.listToSetThenString(data.proDetailsList,'productionno');
          data.processbillno = this.listToSetThenString(data.proDetailsList,'processbillno');
          data.lineid = this.listToSetThenString(data.proDetailsList,'lineid');
          data.linename = this.listToSetThenString(data.proDetailsList,'linename');
          data.screeningSn = this.listToSetThenString(data.proDetailsList,'sn');
          data.screeningLineBoard = this.listToSetThenString(data.proDetailsList,'palletNo');


          putAction('/mes-quality/mesQcIntoWarehouseInspectTask/generateEntity',data).then(res=>{
            if(res.success){
              this.$message.success("操作成功！")
              this.backToIndex();
            }else{
              this.$message.warning(res.msg)
            }
          })
        }

      },


      listToString(list){
        let result = '';
        list.forEach(item=>{
          result+=item;
          result+=',';
        })
        if(list.length>0){
          result = result.substring(0,result.length-1);
        }

        return result;
      },



      listToSetThenString(list,name){
        let result = '';
        let strSet = new Set();

        list.forEach(item=>{
          strSet.add(item[name]);
        })

        for(let str of strSet){
          result+=str+',';
        }
        return result.substring(0,result.length-1);

      }




    },
  };
</script>
<style scoped>
  @import "~@assets/less/common.less";
  .title {
    padding: 8px 12px;
    background: #fafafa;
  }
  .title:not(:first-child) {
    margin-top: 25px;
  }
  .poros-form {
    margin-top: 15px;
  }
  /deep/ .poros-table-body {
    overflow-x: auto !important;
  }
  /deep/ .poros-col {
    min-height: 54px;
  }
  /deep/ .poros-table thead th{
    height:44px;
  }
</style>
